package auth

import (
	"github.com/biezhi/gorm-paginator/pagination"
	"github.com/kataras/iris"
	"iris-demo/core"
)

type UserService struct {
}

func (s UserService) GetById(id uint) (user User, ok bool) {
	ok = !core.DB.First(&user, id).RecordNotFound()
	return user, ok
}

func (s UserService) GetByUsername(username string) (user User, ok bool) {
	ok = !core.DB.Where("username = ?", username).First(&user).RecordNotFound()
	return user, ok
}

func (s UserService) Create(form UserCreateForm) (user User, err error) {
	password, err := core.EncryptPassword(form.Password)
	if err == nil {
		user = User{
			Username: form.Username,
			Password: password,
		}
		err = core.DB.Create(&user).Error
	}
	return
}

func (s UserService) Update(user *User, updateMap iris.Map) (err error) {
	if pwd, ok := updateMap["password"].(string); ok {
		if updateMap["password"], err = core.EncryptPassword(pwd); err != nil {
			return err
		}
	}
	return core.DB.Model(user).Update(updateMap).Error
}

func (s UserService) QuerySet(query string) (paginator *pagination.Paginator) {
	query = "%" + query + "%"
	db := core.DB.Where("username LIKE ?", query).Order("username")
	var users []User
	paginator = pagination.Paging(&pagination.Param{
		DB:      db,
		Page:    1,
		Limit:   3,
		OrderBy: []string{"id desc"},
	}, &users)
	return
}
